import { config } from "@/config"
import { getRouteWithOption } from "@/lib/tool"
import { useMyStore } from "@/stores"
import { MyLoginParam } from "@/types/api/my"
import { usePage } from "@/hooks"
import { event } from "@/lib";

export const useLogin = () => {

    const myStore = useMyStore()
    const { navigate, back, redirect, send } = usePage()
    const isLogin = computed(() => myStore.isLogin)

    //#ifdef H5
    const form = reactive<MyLoginParam<'h5'>>({
        username: '',
        password: ''
    })
    //#endif

    const setLogin = () => {
        //#ifdef MP-WEIXIN
        // https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01
        uni.login({
            success: async (codeRes) => {
                const res = await myStore.login({
                    code: codeRes.code,
                })
                send(event.EVENT_LOGIN_ACCOUNT, res)
                back(1, () => {
                    const page = getRouteWithOption()
                    redirect(page)
                })
            }
        });
        //#endif
        //#ifdef H5
        (async () => {
            if (!form.username || !form.password) {
                return
            }
            const res = await myStore.loginH5(form)
            send(event.EVENT_LOGIN_ACCOUNT, res)
            back(1, () => {
                const page = getRouteWithOption()
                redirect(page)
            })
        })
        //#endif
    }

    const toLoginPage = () => {
        navigate(config.loginPage)
    }
    return {
        /**是否登录 */
        isLogin,
        /**去登陆页 */
        toLoginPage,
        /**登录 */
        setLogin,
        //#ifdef H5
        /**表单 */
        form,
        //#endif
    }
}